package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.order.dto.CreateOrderRequest;
import com.mall.user.IMemberService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.QueryMemberRequest;
import com.mall.user.dto.QueryMemberResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *
 */
@Slf4j
@Component
public class ValidateHandler extends AbstractTransHandler {

    @Reference(check = false)
    private IMemberService memberService;

    /**
     * 验证用户合法性
     * @return
     */

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
//        CreateOrderContext createOrderContext = (CreateOrderContext) context;
//        Long userId = createOrderContext.getUserId();
//        String verify = memberService.validateMember(userId);
//        if ("N".equals(verify)) {
//            throw new BizException(SysRetCodeConstants.PERMISSION_DENIED.getCode(),SysRetCodeConstants.PERMISSION_DENIED.getMessage());
//        }
//        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
//        for (CartProductDto cartProductDto : cartProductDtoList) {
//            Long productId = cartProductDto.getProductId();
//            Long productNum = cartProductDto.getProductNum();
//
//            Stock stock = stockMapper.selectStock(productId);
//            Long stockCount = stock.getStockCount();
//            if (stockCount < productNum) {
//                throw new BizException(OrderRetCode.DB_SAVE_EXCEPTION.getCode(),OrderRetCode.DB_SAVE_EXCEPTION.getMessage());
//            }
//        }
        log.info("begin ValidateHandler :context:" + context);
        CreateOrderContext createOrderContext = (CreateOrderContext) context;


        //验证是否存在该用户
        QueryMemberRequest queryMemberRequest = new QueryMemberRequest();
        queryMemberRequest.setUserId(createOrderContext.getUserId());
        QueryMemberResponse queryMemberResponse = memberService.queryMemberById(queryMemberRequest);

        //如果的的码值和其相等,设置其用户名为用户名
        if(SysRetCodeConstants.SUCCESS.getCode().equals(queryMemberResponse.getCode())){
            createOrderContext.setBuyerNickName(queryMemberResponse.getUsername());
        }else{
            throw new BizException(queryMemberResponse.getCode(), queryMemberResponse.getMsg());
        }
        return true;
    }
}
